package com.bjpowernode.web;

import com.alibaba.excel.EasyExcel;
import com.bjpowernode.model.TClue;
import com.bjpowernode.query.ClueQuery;
import com.bjpowernode.result.R;
import com.bjpowernode.service.ClueService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ClueController {

    @Resource
    private ClueService clueService;

    /**
     * 编辑线索
     * @param clueQuery clueQuery
     * @param token token
     * @return R
     */
    @PutMapping(value = "/api/clue")
    public R editClue(ClueQuery clueQuery, @RequestHeader("Authorization") String token) {
        clueQuery.setToken(token);
        int update = clueService.updateClue(clueQuery);
        return update > 0 ? R.OK(): R.FAIL();
    }

    /**
     * 根据Id查询线索信息
     * @param id id
     * @return R
     */
    @GetMapping(value = "/api/clue/detail/{id}")
    public R loadClue(@PathVariable("id") Integer id) {
        TClue tClue = clueService.getClueById(id);
        return R.OK(tClue);
    }

    /**
     * 录入线索
     * @param clueQuery clueQuery
     * @param token token
     * @return R
     */
    @PostMapping(value = "/api/clue")
    public R addClue(ClueQuery clueQuery, @RequestHeader("Authorization") String token) {
        clueQuery.setToken(token);
        int save = clueService.addClue(clueQuery);
        return save > 0 ? R.OK(): R.FAIL();
    }

    /**
     * 验证手机号是否已录入
     * @param phone 手机号
     * @return R
     */
    @GetMapping(value = "/api/clue/{phone}")
    public R checkPhone(@PathVariable("phone")String phone) {
        Boolean check = clueService.checkPhone(phone);
        return check ? R.OK() : R.FAIL();
    }

    /**
     * 线索导入excel文件
     * @return R
     */
    @PostMapping(value = "/api/importExcel")
    public R importExcel(MultipartFile file, @RequestHeader("Authorization")String token) {  // file的名字要和前端formData里面的名字相同
        clueService.importExcel(file, token);
        return R.OK();
    }

    /**
     * 线索管理分页列表展示
     * @param current 当前页
     * @return R
     */
    @PreAuthorize(value = "hasAuthority('clue:list')")
    @GetMapping(value = "/api/clues")
    public R cluePage(@RequestParam(value = "current", required = false) Integer current) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TClue> pageInfo = clueService.getClueByPage(current);
        return R.OK(pageInfo);
    }

}
